<template>
  <div class="chat-container">
    <div class="nav-sidebar">
      <div class="nav-header">
        <div class="user-avatar">
          <img :src="$store.state.userInfo?.avatar" />
        </div>
      </div>
      <div class="nav-menu">
        <div
          class="nav-item chat-icon"
          :class="{ active: currentNav === 'chat' }"
          @click="switchNav('chat')"
        >
          <i class="fas fa-comment"></i>
          <span class="nav-text">聊天</span>
        </div>
        <div
          class="nav-item friends-icon"
          :class="{ active: currentNav === 'friends' }"
          @click="switchNav('friends')"
        >
          <i class="fas fa-user-friends"></i>
          <span class="nav-text">好友</span>
        </div>
        <div
          class="nav-item groups-icon"
          :class="{ active: currentNav === 'groups' }"
          @click="switchNav('groups')"
        >
          <i class="fas fa-users"></i>
          <span class="nav-text">群聊</span>
        </div>
        <!-- 设置选项 -->
        <div
          class="nav-item settings-icon"
          :class="{ active: currentNav === 'settings' }"
          @click="switchNav('settings')"
        >
          <i class="fas fa-cog"></i>
          <span class="nav-text">设置</span>
        </div>
        
      </div>
      <!-- <div class="nav-bottom">
        <a
          class="nav-item"
          href="https://gitee.com/zheng-yuhang12/new_forum_system"
          target="_blank"
          title="查看源码"
        >
          <i class="fab fa-github"></i>
          <span class="nav-text">源码</span>
        </a>
      </div> -->
    </div>

    <!-- 遮罩层 -->
    <div
      v-if="isMobile && !isListHidden"
      class="mobile-overlay"
      @click="toggleList"
    ></div>

    <div
      class="chat-list-container"
      :class="{ 'mobile-hidden': isMobile && isListHidden }"
    >
      <div class="search-box" v-if="currentNav === 'chat' || currentNav === 'friends' || currentNav === 'groups'">
        <input type="text" placeholder="搜索" />
      </div>
      <!-- 替换设置页面的搜索框为快捷操作组件 -->
      <div class="quick-actions" v-else-if="currentNav === 'settings'">
        <div class="quick-actions-header">
          <h3>快捷操作</h3>
        </div>
        <div class="quick-actions-grid">
          <div class="quick-action-item" @click="clearChatHistory">
            <i class="fas fa-trash-alt"></i>
            <span>清空聊天记录</span>
          </div>
          <div class="quick-action-item" @click="exportChatData">
            <i class="fas fa-file-export"></i>
            <span>导出聊天数据</span>
          </div>
          <div class="quick-action-item" @click="checkForUpdates">
            <i class="fas fa-sync-alt"></i>
            <span>检查更新</span>
          </div>
          <div class="quick-action-item" @click="showHelp">
            <i class="fas fa-question-circle"></i>
            <span>使用帮助</span>
          </div>
          <!-- 新增快捷操作项 -->
          <div class="quick-action-item" @click="backupSettings">
            <i class="fas fa-cloud-upload-alt"></i>
            <span>备份设置</span>
          </div>
          <div class="quick-action-item" @click="restoreSettings">
            <i class="fas fa-cloud-download-alt"></i>
            <span>恢复设置</span>
          </div>
          <div class="quick-action-item" @click="viewStatistics">
            <i class="fas fa-chart-bar"></i>
            <span>查看统计</span>
          </div>
          <div class="quick-action-item" @click="feedback">
            <i class="fas fa-comment-dots"></i>
            <span>意见反馈</span>
          </div>
          <!-- 再新增4个快捷操作项 -->
          <div class="quick-action-item" @click="changeTheme">
            <i class="fas fa-palette"></i>
            <span>切换主题</span>
          </div>
          <div class="quick-action-item" @click="manageEmojis">
            <i class="fas fa-smile"></i>
            <span>表情管理</span>
          </div>
          <div class="quick-action-item" @click="securitySettings">
            <i class="fas fa-shield-alt"></i>
            <span>安全设置</span>
          </div>
          <div class="quick-action-item" @click="aboutSystem">
            <i class="fas fa-info-circle"></i>
            <span>关于系统</span>
          </div>
        </div>
      </div>
      <div class="chat-list">
        <template v-if="currentNav === 'chat'">
          <div
            v-for="chat in chatList"
            :key="chat.id"
            class="chat-item"
            :class="{ active: currentChat.id === chat.id }"
            @click="switchChatRoom(chat)"
          >
            <div class="avatar">
              <img :src="chat.avatar || '/default-group-avatar.png'" />
              <div v-if="chat.unreadCount" class="unread-badge">
      {{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}
    </div>
            </div>
            <div class="chat-info">
              <div class="name">{{ chat.name }}</div>
              <div class="last-message" v-html="chat.lastMessage"></div>
            </div>
            <div class="meta">
              <div class="time">{{ chat.lastTime }}</div>
            </div>
          </div>
        </template>
        <template v-else-if="currentNav === 'friends'">
          <div
            v-for="friend in friendsList"
            :key="friend.id"
            class="friend-item"
            :class="{
              active: selectedFriend && selectedFriend.id === friend.id,
            }"
            @click="selectFriend(friend)"
          >
            <div class="avatar">
              <img :src="friend.avatar" />
            </div>
            <div class="friend-info">
              <div class="name">{{ friend.name }}</div>
            </div>
          </div>
        </template>
        <!-- 群聊列表：只显示博客交流群 -->
        <template v-else-if="currentNav === 'groups'">
          <div class="groups-info-banner">
            <i class="fas fa-info-circle"></i>
            <div class="groups-info-text">
              <p>目前只有一个官方群聊：博客交流群</p>
              <p class="info-subtext">暂不支持创建新群聊</p>
            </div>
          </div>
          <div
            v-for="group in blogGroups"
            :key="group.id"
            class="chat-item"
            :class="{ active: currentChat.id === group.id }"
            @click="switchChatRoom(group)"
          >
            <div class="avatar">
              <img :src="group.avatar || '/default-group-avatar.png'" />
              <div v-if="group.unreadCount" class="unread-badge">
                {{ group.unreadCount > 99 ? '99+' : group.unreadCount }}
              </div>
            </div>
            <div class="chat-info">
              <div class="name">{{ group.name }}</div>
              <div class="last-message" v-html="group.lastMessage"></div>
            </div>
            <div class="meta">
              <div class="time">{{ group.lastTime }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <div class="chat-main" v-if="currentNav === 'chat'">
      <div class="chat-header">
        <div class="user-info">
          <div class="toggle-list-btn" @click="toggleList" v-if="isMobile">
            <i class="fas fa-bars"></i>
          </div>
          <h3>{{ currentChat.name || '请选择聊天室' }}</h3>
        </div>
      </div>

      <!-- 添加未选择聊天室时的提示界面 -->
      <div v-if="!currentChat.id" class="no-chat-selected">
        <i class="fas fa-comments"></i>
        <p>请选择一个聊天室开始聊天</p>
      </div>
          
      <div v-else class="messages chat-messages" ref="messageContainer">
        <!-- 添加加载更多按钮 -->
        <div v-if="hasMore" class="load-more-wrapper">
          <button class="load-more-btn" @click="loadMoreMessages" :disabled="loading">
            <i v-if="loading" class="fas fa-spinner fa-spin"></i>
            {{ loading ? '加载中...' : '加载更多' }}
          </button>
        </div>

        <div
          v-for="(msg, index) in currentChat.messages"
          :key="generateUniqueKey(msg, index)"
          :class="[
            'message',
            { 'message-self': msg.senderId === $store.state.userInfo?.id },
            { 'active-message': msg.id === currentChat.id }
          ]"
        >
     
          <div
            class="avatar"
            @contextmenu.prevent="handleAvatarContextMenu(msg, $event)"
          >
            <img :src="msg.avatar!= null ? msg.avatar : 'https://zzzyh-forum-system.oss-cn-hangzhou.aliyuncs.com/robot.png'" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <div
                v-if="
                  currentChat.isgroup && msg.senderId !== $store.state.userInfo?.id
                "
                class="sender-name"
              >
                <span :class="msg.senderId === 1 ? 'user-name': msg.senderId === 2 ? 'assistant-name': ''" >{{ msg.name || 'robot' }}</span>
                <span v-if="msg.senderId === 1" class="author-tag">作者</span>
                <span v-if="msg.senderId === 2" class="assistant-tag">A I</span>
                <span class="message-time">{{ msg.time }}</span>
                <span class="location">{{ splitIpAddress(msg.location) }}</span>
                <span class="gender" v-if="msg.sex"><i :class="msg.sex === 1 ? 'fas fa-mars' : 'fas fa-venus'"></i></span>
              </div>
            </div>
            <div v-if="msg.isRecalled" class="message-recalled">
              <span>消息已撤回</span>
            </div>
            <template v-else>
              <div
                :data-message-id="msg.id"
                v-if="msg.type === 'text'"
                class="message-text"
                v-html="formatMessageContent(msg.content)"
                @contextmenu.prevent="showMessageActions(msg, $event)"
              ></div>
              
              <img
                v-else-if="msg.type === 'image'"
                v-lazy="msg.content"
                :key="'img-' + (msg.id || index)"
                class="message-image"
                @click="previewImage(msg.content)"
                @load="handleImageLoad"
                @contextmenu.prevent="showMessageActions(msg, $event)"
              />
              <div
                v-else-if="msg.type === 'file'"
                class="message-file"
                @contextmenu.prevent="showMessageActions(msg, $event)"
              >
                <i class="fas fa-file-download"></i>
                <div class="file-info">
                  <a href="javascript:void(0)" >{{
                    msg.fileName
                  }}</a>
                  <span class="file-size">{{
                    formatFileSize(msg.fileSize)
                  }}</span>
                </div>
              </div>
              <div
                v-else-if="msg.type === 'audio'"
                class="message-audio"
                @contextmenu.prevent="showMessageActions(msg, $event)"
              >
                <div
                  class="audio-bubble"
                  @click="toggleAudioPlayback(msg, $event)"
                >
                  <i
                    :class="['fas', msg.isPlaying ? 'fa-pause' : 'fa-play']"
                  ></i>
                  <span>{{ msg.duration }}秒</span>
                </div>
              </div>
            </template>
             <!-- 新增引用消息显示 -->
             <div v-if="msg.replyId && !msg.isRecalled" class="reply-message" @click="scrollToMessage(msg.replyId)">
              <span class="reply-content">
                <i class="el-icon-top"></i>{{msg.replyUserName}}：{{msg.replyContent}}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 只有在选择了聊天室时才显示输入区域 -->
      <div v-if="currentChat.id" class="chat-input" style="position: relative;">
        <!-- 新增被回复消息显示 -->
        <div v-if="selectedReplyMessage" class="reply-preview">
          <span class="reply-title">回复: {{ selectedReplyMessage.content }}</span>
          <i class="fas fa-times" @click="cancelReply"></i>
        </div>
        <div class="input-toolbar">
          <mj-emoji size="1.1rem" class="emoji-picker" @select="insertEmoji" />

          <!-- 新增文件上传按钮 -->
          <label
            class="toolbar-btn file-upload-btn"
            for="file-upload"
            title="上传文件"
          >
            <i class="fas fa-folder"></i>
          </label>
          <input
            id="file-upload"
            type="file"
            style="display: none"
            @change="handleFileUpload"
          />

          <!-- 新增语音录制按钮 -->
          <label
            @click="toggleVoiceMode"
            class="toolbar-btn voice-toggle-btn"
            title="语音输入"
          >
            <i class="fas fa-microphone"></i>
          </label>
        </div>

        <div class="input-area">
          <template v-if="isVoiceMode">
            <!-- 改进的语音录制按钮 -->
            <button
              :class="['voice-record-btn', { recording: isRecording }]"
              @mousedown="startRecording"
              @mouseup="stopRecording"
              @mouseleave="cancelRecording"
              @touchstart="startRecording"
              @touchend="stopRecording"
            >
              {{ isRecording ? "正在说话中..." : "按住说话" }}
            </button>
          </template>
          <template v-else>
            <div class="input-wrapper">
              <div class="paste-preview" v-if="pastedImages.length > 0">
                <div v-for="(image, index) in pastedImages" :key="index" class="pasted-image">
                  <img :src="image.preview"  @click="previewImage(image.preview)" />
                  <i class="fas fa-times" @click="removeImage(index)"></i>
                </div>
              </div>
              <div
                ref="messageInput"
                class="message-input"
                contenteditable="true"
                @input="handleInput"
                @keydown.enter.prevent="handleEnterKey"
                @keydown="handleMentionKeydown"
                @paste="handlePaste"
                :placeholder="`输入消息...`"
              ></div>
            </div>
          </template>

          <button
            v-if="!isVoiceMode"
            @click="sendMessage"
            :disabled="(!messageText.trim() && pastedImages.length === 0) || countdown > 0"
          >
            <template v-if="countdown > 0"> {{ countdown }}s </template>
            <i v-else class="fas fa-paper-plane"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 设置页面 -->
    <div class="settings-main" v-else-if="currentNav === 'settings'">
      <div class="settings-header">
        <h2>聊天设置</h2>
      </div>
      <div class="settings-content">
        <el-card class="settings-card">
          <div slot="header" class="clearfix">
            <span>通用设置</span>
          </div>
          <el-form :model="chatSettings" label-width="120px">
            <el-form-item label="消息提醒">
              <el-switch
                v-model="chatSettings.notifications"
                active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
            <el-form-item label="声音提醒">
              <el-switch
                v-model="chatSettings.sound"
                active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
            <el-form-item label="消息预览">
              <el-switch
                v-model="chatSettings.preview"
                active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
            <el-form-item label="Enter键发送">
              <el-switch
                v-model="chatSettings.enterToSend"
                active-text="开启"
                inactive-text="关闭">
              </el-switch>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="settings-card">
          <div slot="header" class="clearfix">
            <span>隐私设置</span>
          </div>
          <el-form :model="privacySettings" label-width="120px">
            <el-form-item label="允许添加好友">
              <el-switch
                v-model="privacySettings.allowAddFriends"
                active-text="允许"
                inactive-text="不允许">
              </el-switch>
            </el-form-item>
            <el-form-item label="显示在线状态">
              <el-switch
                v-model="privacySettings.showOnlineStatus"
                active-text="显示"
                inactive-text="隐藏">
              </el-switch>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="settings-card">
          <div slot="header" class="clearfix">
            <span>关于</span>
          </div>
          <div class="about-section">
            <p>聊天版本: v1.0.0</p>
            <p>© 2025 聊天系统</p>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 好友信息显示区域 -->
    <div v-if="selectedFriend && currentNav === 'friends'" class="friend-details">
      <!-- 使用头像展示组件 -->
    <div class="avatar-wrapper">
      <el-avatar 
        :src="selectedFriend.avatar" 
        :size="80" 
        shape="circle"
      />
    </div>
      <h3>{{ selectedFriend.name }}</h3>
      <p class="signature">
        签名：{{ selectedFriend.signature || "这个人很懒，什么都没写。" }}
      </p>
      <p class="gender">性别：{{ selectedFriend.gender || "未知" }}</p>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-message"
        @click="sendMessageToFriend(selectedFriend.id)"
        >发送信息</el-button
      >
      <el-button
        type="danger"
        size="small"
        icon="el-icon-delete"
        @click="deleteFriend"
        >删除好友</el-button
      >
    </div>

    <!-- 新增：在好友页面未选择好友时显示提示 -->
    <div v-else-if="currentNav === 'friends' && !selectedFriend" class="no-friend-selected">
      <i class="fas fa-user-friends"></i>
      <p>请选择好友</p>
    </div>
    
    <div v-else-if="currentNav === 'groups'" class="no-group-selected">
      <div class="group-info-container">
        <h3>博客交流群</h3>
        <div class="group-description">
          <p>欢迎加入我们的官方聊天室！这里是技术交流和分享的乐园。</p>
          <div class="group-features">
            <div class="feature-item">
              <i class="fas fa-comments"></i>
              <span>技术交流</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-share-alt"></i>
              <span>经验分享</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-question-circle"></i>
              <span>问题讨论</span>
            </div>
          </div>
        </div>
        
        <div class="group-rules">
          <h4><i class="fas fa-book"></i> 群规说明</h4>
          <div class="rules-container" @wheel.prevent="handleScroll">
            <ul>
              <li>请保持友善交流，禁止人身攻击</li>
              <li>禁止发布广告、垃圾信息</li>
              <li>禁止传播违法不良信息</li>
              <li>禁止刷屏和恶意灌水</li>
              <li>请遵守相关法律法规</li>
            </ul>
          </div>
        </div>
        
        <!-- <div class="group-note">
          <p><i class="fas fa-info-circle"></i> 目前只有一个官方群聊：博客交流群</p>
          <p class="note-subtext">暂不支持创建新群聊</p>
        </div> -->
      </div>
    </div>

    <!-- 图片预览 -->
    <mj-image-preview ref="imagePreview" />

    <div
      v-if="showActionsMenu"
      class="message-actions-menu"
      :style="actionMenuPosition"
    >
      <template v-if="selectedMessage">
        <!-- 新增回复选项 -->
        <div class="action-item" v-if="selectedMessage.senderId !== $store.state.userInfo?.id 
          && selectedMessage.isRecalled === false" @click="replyToMessage">
          <i class="fas fa-reply"></i>
          回复
        </div>
        <div
          v-if="selectedMessage.senderId !== $store.state.userInfo?.id"
          class="action-item"
          @click="mentionUser"
        >
          <i class="fas fa-at"></i>
          TA
        </div>
        <div
          v-if="
            !selectedMessage.isRecalled &&
            selectedMessage.senderId === $store.state.userInfo?.id
          "
          class="action-item"
          @click="recallMessage"
        >
          <i class="fas fa-undo"></i>
          撤回
        </div>
        <div class="action-item" @click="handleSearch">
          <i class="fas fa-search"></i>
          搜索
        </div>
        <div class="action-item" @click="handleDownloadFile" v-if="selectedMessage.type === 'file'">
          <i class="fas fa-download"></i>
          下载
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { sendMsg, getChatMsgListApi, recallMsgApi ,getFriendsListApi,getRoomsListApi,getRoomWithUserApi,getFriendInfoApi,getLastMsg,updateUnreadCount} from "@/api/chat";
import { formatTime } from "@/utils/time";
import { uploadFileApi } from "@/api/file";
import { disableScroll, enableScroll } from "@/utils/scroll";
import { showLoading, hideLoading } from "@/utils/loading";
import { marked } from 'marked'; // 使用命名导入
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'


export default {
  name: "Chat",
  data() {
    return {
      currentNav: "chat",
      chatList: [
        {
          id: 1,
          name: "博客交流群",
          avatar: this.$store.state.webSiteInfo?.logo || "/default-group-avatar.png",
          lastMessage: "",
          lastTime: "",
          friendId :"",
        },
      ],
      friendsList: [
        {
          id: 1,
          name: "张三",
          avatar:
            "https://foruda.gitee.com/avatar/1677004143848886034/2106773_hhf1237_1647845148.png",
          signature: "热爱生活，热爱编程。",
          gender: "男",
        },
        {
          id: 2,
          name: "李四",
          avatar:
            "https://foruda.gitee.com/avatar/1677079463351115261/7467101_unique_perfect_1638710768.png",
          signature: "旅行是我的灵魂。",
          gender: "女",
        },
      ],
      // 博客交流群专用列表
      blogGroups: [
        {
          id: 1,
          name: "博客交流群",
          avatar: this.$store.state.webSiteInfo?.logo || "/default-group-avatar.png",
          lastMessage: "欢迎加入博客交流群！",
          lastTime: "刚刚",
          isgroup: true,
        }
      ],
      messageText: "",
      ws: null, // WebSocket实例
      currentChat: {
        id: 1,
        name: "博客交流群",
        avatar: this.$store.state.webSiteInfo.logo,
        lastMessage: "",
        lastTime: "12:30",
        isgroup: true,
        messages: [
          {
            id: 1,
            type: "",
            content: "",
            isPlaying: false, 
          },
        ],
      },
      showActionsMenu: false,
      selectedMessage: null,
      actionMenuPosition: {
        top: "0px",
        left: "0px",
      },
      params: {
        pageNum: 1,
        pageSize: 10,
        roomId: 1,
      },
      loading: false, // 是否正在加载更多消息
      hasMore: true, // 是否还有更多消息
      countdown: 0, // 倒计时秒数
      countdownTimer: null, // 计时器实例
      heartbeatTimer: null, // 心跳定时器
      heartbeatInterval: 30000, // 心跳间隔，30秒
      reconnectAttempts: 0, // 重连次数
      maxReconnectAttempts: 5, // 最大重连次数
      shouldReconnect: true, // 是否需要重连的标志
      shouldScrollToBottom: true, // 添加新标志来控制是否滚动到底部
      isMobile: false,
      isListHidden: false,
      selectedFriend: null, // 用于存储选中的好友信息
      isVoiceMode: false, // 新增语音模式状态
      mediaRecorder: null,
      audioChunks: [],
      isRecording: false, // 新增录音状态
      audioStartTime: null, // 新增音频开始时间
      audioEndTime: null, // 新增音频结束时间
      audio: null,
      selectedReplyMessage: null, // 新增字段，用于存储回复的消息
      pastedImages: [], // 存储粘贴的图片
      // 聊天设置
      chatSettings: {
        notifications: true,
        sound: true,
        preview: true,
        enterToSend: true
      },
      // 隐私设置
      privacySettings: {
        allowAddFriends: true,
        showOnlineStatus: true
      }
    };
  },

  

  //监听this.$store.state.userInfo的变化
  watch: {
    "$store.state.userInfo": {
      handler(newVal, oldVal) {
        // 有值就连接ws, 没有就移除
        if (newVal) {
          this.init();
        } else {
          this.$router.push('/login')
          if (this.ws) {
            this.ws.close();
          }
        }
      },
      deep: true,
    },
    // 监听网站信息变化，更新头像
    "$store.state.webSiteInfo": {
      handler(newVal) {
        if (newVal && newVal.logo) {
          // 更新chatList中的博客交流群头像
          const blogChat = this.chatList.find(chat => chat.id === 1);
          if (blogChat) {
            blogChat.avatar = newVal.logo;
          }
          
          // 更新blogGroups中的博客交流群头像
          const blogGroup = this.blogGroups.find(group => group.id === 1);
          if (blogGroup) {
            blogGroup.avatar = newVal.logo;
          }
        }
      },
      deep: true,
    },
    // 监听聊天设置变化，自动保存
    chatSettings: {
      handler(newVal) {
        localStorage.setItem('chatSettings', JSON.stringify(newVal));
      },
      deep: true
    },
    // 监听隐私设置变化，自动保存
    privacySettings: {
      handler(newVal) {
        localStorage.setItem('privacySettings', JSON.stringify(newVal));
      },
      deep: true
    }
  },
  async created() {
    // 如果用户信息存在，则连接WebSocket
    if (!this.$store.state.userInfo) {
      this.$router.push('/login')
      return;
    }
    
    // 在nextTick后禁用滚动,确保DOM已经渲染
    this.$nextTick(() => {
      disableScroll();
    });
    
    this.checkMobile();
    window.addEventListener("resize", this.checkMobile);
    
    // 确保默认导航为聊天
    this.currentNav = "chat";
    
    // 获取聊天室列表
    await this.getRoomsList();
    console.log(this.chatList);
    
    // 默认不选择任何聊天室，提示用户选择聊天室开始聊天
    // 清空currentChat信息
    this.currentChat = {
      id: null,
      name: "",
      avatar: "",
      lastMessage: "",
      lastTime: "",
      isgroup: false,
      messages: []
    };
    
    // 初始化设置
    // this.loadSettings();
    
    // 初始化WebSocket连接
    this.init();
    
    // 处理从搜索页面跳转过来的私信请求
    if (this.$route.query.userId) {
      this.sendMessageToFriend(parseInt(this.$route.query.userId))
    }
  },
  beforeDestroy() {
    this.shouldReconnect = false; // 设置不再重连
    this.stopHeartbeat(); // 清理心跳定时器
    if (this.ws) {
      this.ws.close();
    }
    // 移除滚动事件监听
    const container = this.$refs.messageContainer;
    if (container) {
      container.removeEventListener("scroll", this.handleScroll);
    }
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
    // 确保在组件销毁时启用滚动
    enableScroll();
    window.removeEventListener("resize", this.checkMobile);
  },
  methods: {


     // 切换聊天室
  async switchChatRoom(room) {
    // 如果点击的是当前聊天室，不执行任何操作
    if (this.currentChat.id === room.id) return;
    
    // 设置当前聊天室
    this.currentChat = room;
    // 清除未读消息计数
  if (room.unreadCount) {
    room.unreadCount = 0;
    updateUnreadCount(room.id,0,this.$store.state.userInfo.id);
  }
    
    // 重置分页参数
    this.params.pageNum = 0;
    this.params.roomId = room.id;
    // console.log(this.params);
    this.loading = false; // 重置loading状态
    this.hasMore = true; // 重置hasMore状态
    
    console.log("切换聊天室",room);
    
    
    // 清空当前消息列表
      this.currentChat.messages = [];
    
    // 重新加载消息
    // await this.getChatList();
    this.$nextTick(async () => {
      await this.loadMoreMessages();
      // 滚动到底部
      this.scrollToBottom();
    });
  },

    async getRoomsList() {
      try {
        const res = await getRoomsListApi(this.$store.state.userInfo.id);
        res.data.forEach((room) => {
          room.lastTime = formatTime(room.lastTime);
        });
        this.chatList = res.data;
        this.chatList.forEach(async (room) => {
          if(room.isgroup === 2){
            const content = room.content;
            console.log(content);
            const userIds = content.split("-");
            if (userIds.length === 2) {
              const userId1 = parseInt(userIds[0]);
              const userId2 = parseInt(userIds[1]);
              // 确定好友ID（不是当前登录用户的那个ID）
              const currentUserId = this.$store.state.userInfo.id;
              const friendId = userId1 === currentUserId ? userId2 : userId1;
              // 你可以在这里使用friendId进行后续操作
              console.log("好友ID:", friendId);
              room.friendId = friendId;
              const friend = await getFriendInfoApi(friendId)
              console.log("好友信息:", friend);
              room.name = friend.data.name;
              room.avatar = friend.data.avatar;
            }
          }
          // console.log("房间信息:", room);

          room.lastMessage =
            room.type === "text"
            ? room.lastMessage
            : room.type === "image"
            ? "[图片]"
            : room.type === "audio"
            ? "[语音] " + room.messages[0].duration + "秒"
            : "[文件]";
          
        });
        console.log(this.chatList);
        
        
      } catch (error) {
        console.log(error);
      }
    },
    

    async getFriendsList() {
      try {
        const res = await getFriendsListApi(this.$store.state.userInfo.id);
        this.friendsList = res.data;
      } catch (error) {
        console.log(error);
      }
    },

    async switchNav(nav) {
      this.currentNav = nav;
      this.selectedFriend = null;
      
      if (nav === "chat") {
        this.$nextTick(() => {
          // 只有在选择了聊天室时才滚动到底部
          if (this.currentChat.id) {
            this.scrollToBottom();
          }
          // 重新添加滚动事件监听器
          const container = this.$refs.messageContainer;
          if (container) {
            container.addEventListener("scroll", this.handleScroll);
          }
          // 重置加载状态
          this.hasMore = true;
          this.params.pageNum = 1;
        });
        await this.getRoomsList()
      } else if (nav === "friends") { 
        await this.getFriendsList();
      } else if (nav === "groups") {
        // 群聊页面特殊处理：只显示博客交流群
        // 不需要加载其他群聊，因为我们只有一个固定的博客交流群
        console.log("切换到群聊页面，只显示博客交流群");
      } else if (nav === "settings") {
        // 加载设置
        // this.loadSettings();
      }
    },
    /**
     * 初始化
     */
    async init() {
      this.connectWebSocket();
      // 只有在选择了聊天室时才加载聊天列表
      if (this.currentChat.id) {
        await this.getChatList();
      }

      // 添加滚动事件监听
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        if (container) {
          container.addEventListener("scroll", this.handleScroll);
        }

        // 只有在选择了聊天室时才滚动到底部
        if (this.currentChat.id) {
          setTimeout(() => {
            this.scrollToBottom();
          }, 300);
        }
      });
    },
    /**
     * 获取聊天列表
     */
    async getChatList() {
      // showLoading();
      this.params.roomId = this.currentChat.id;
      const res = await getChatMsgListApi(this.params);
      
      this.currentChat.messages = res.data.records;
      // console.log(this.currentChat.messages);
      
      if (this.params.pageNum === 1 && this.currentChat.messages.length > 0) {
        this.currentChat.lastTime = formatTime(
          this.currentChat.messages[0].time
        );
        if(this.currentChat.messages[0].isRecalled){
          this.currentChat.lastMessage = "消息已撤回";
        }else{
          this.currentChat.lastMessage =
            this.currentChat.messages[0].type === "text"
            ? this.currentChat.messages[0].content
            : this.currentChat.messages[0].type === "image"
            ? "[图片]"
            : this.currentChat.messages[0].type === "audio"
            ? "[语音] " + this.currentChat.messages[0].duration + "秒"
            : "[文件]";
        }
      }
      //获取到的数据是最新时间的，应该要把这个顺序反过来
      this.currentChat.messages.reverse();
      this.currentChat.messages.forEach((msg) => {
        msg.time = formatTime(msg.time);
      });

      this.handlePreCode();
      // hideLoading();
    },
    /**
     * 连接WebSocket
     */
    connectWebSocket() {
      try {
        const wsUrl = import.meta.env.VITE_APP_WEBSOCKET_API;
        const uri = wsUrl + this.$store.state.userInfo.id
        console.log("uri:", uri);
        this.ws = new WebSocket(uri);
        this.ws.onopen = () => {
          console.log("WebSocket连接已建立");
          this.reconnectAttempts = 0;
          this.startHeartbeat();
        };

        this.ws.onmessage = (event) => {
          console.log("收到原始消息:", event.data);
          try {
            const message = JSON.parse(event.data);
            // 如果是心跳响应，则不处理
            if (message.type === "ping") {
              return;
            }
            this.handleIncomingMessage(message);
          } catch (error) {
            console.error("解析消息失败:", error);
          }
        };

        this.ws.onclose = (event) => {
          console.log("WebSocket连接已关闭");
          console.log("关闭代码:", event.code);
          console.log("关闭原因:", event.reason);
          this.stopHeartbeat(); // 停止心跳
          this.reconnect(); // 尝试重连
        };

        this.ws.onerror = (error) => {
          console.error("WebSocket错误:", error);
          this.stopHeartbeat(); // 停止心跳
        };
      } catch (error) {
        console.error("建立WebSocket连接失败:", error);
      }
    },

    /**
     * 处理接收到的消息
     */
    async handleIncomingMessage(message) {
      console.log("收到消息:", message);

      if (typeof message === "string") {
        try {
          message = JSON.parse(message);
        } catch (e) {
          console.error("消息格式错误:", e);
          return;
        }
      }
      if (message.isRecalled) {
        const index = this.currentChat.messages.findIndex(
          (msg) => msg.id === message.id
        );
        if (index !== -1) {
          this.currentChat.messages[index].content = message.content;
          this.currentChat.messages[index].isRecalled = message.isRecalled;
        }
        return;
      }
      if (message.type === "text") {
        message.content = message.content.replace(
          /@(\S+)\s/g,
          "<mention>@$1</mention> "
        );
      }

      console.log("处理后的消息:", message);
      
      const newMessage = {
        id: message.id || Date.now() + Math.random(), // 确保每条消息都有唯一ID
        type: message.type || "text",
        content: message.content,
        time: formatTime(new Date()),
        senderId: message.senderId,
        name: message.name,
        avatar: message.avatar,
        sex: message.sex,
        location: message.location,
        fileSize: message.fileSize,
        fileName: message.fileName,
        duration: message.duration,
        isPlaying: false, // 确保初始化时存在
        replyId: message.replyId || null, 
        replyContent: message.replyContent || null,
        replyUserName: message.replyUserName || null,
      };

      // this.currentChat.messages.push(newMessage);
      // this.currentChat.lastMessage =
      //   message.type === "text"
      //     ? message.content
      //     : message.type === "image"
      //     ? "[图片]"
      //     : message.type === "audio"
      //     ? "[语音] " + message.duration + "秒"
      //     : "[文件]";
      // this.currentChat.lastTime = "刚刚";
      // this.shouldScrollToBottom = true;

      // this.$nextTick(() => {
      //   this.scrollToBottom();
      // });
      // 查找目标聊天室（根据roomId匹配）
  const targetChat = this.chatList.find(chat => chat.id === message.roomId);
  
  if (targetChat) {
    // 将消息添加到对应聊天室
    if (!targetChat.messages) {
      targetChat.messages = [];
    }
    targetChat.messages.push(newMessage);
    
    // 更新聊天室的最后消息和时间
    targetChat.lastMessage = message.type === "text"
      ? message.content
      : message.type === "image"
      ? "[图片]"
      : message.type === "audio"
      ? "[语音] " + message.duration + "秒"
      : "[文件]";
    targetChat.lastTime = "刚刚";
    
    // 处理未读消息提示
    if (this.currentChat.id !== targetChat.id) {
      // 如果消息不是来自当前聊天室，增加未读计数
      if (!targetChat.unreadCount) {
        targetChat.unreadCount = 1;
      } else {
        targetChat.unreadCount += 1;
      }
      console.log('更新未读计数:', targetChat.unreadCount);
      await updateUnreadCount(targetChat.id,targetChat.unreadCount,this.$store.state.userInfo.id);
    } else {
      // 如果是当前聊天室，执行滚动操作
      this.shouldScrollToBottom = true;
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    }
  }
      setTimeout(() => {
        this.handlePreCode();
      }, 100);
    },
    /**
     * 处理代码块
     */
    async handlePreCode(){
      await this.$nextTick()
      document.querySelectorAll('pre code').forEach((block) => {
        hljs.highlightBlock(block)
      })

      this.addCopyButtons();
    },

     /**
     * 添加复制按钮
     */
     addCopyButtons() {
      const codeBlocks = document.querySelectorAll('.message-content pre')
      if (!codeBlocks.length) return

      codeBlocks.forEach(pre => {
        // 检查是否已经添加过复制按钮
        if (pre.querySelector('.code-header')) return

        // 创建复制按钮容器
        const buttonWrapper = document.createElement('div')
        buttonWrapper.className = 'code-header'

        // 创建复制按钮
        const copyButton = document.createElement('button')
        copyButton.className = 'copy-button'
        copyButton.innerHTML = '<i class="fas fa-copy"></i> 复制'
        copyButton.title = '复制代码'

        // 添加点击事件
        copyButton.addEventListener('click', async () => {
          try {
            const code = pre.querySelector('code')
            await navigator.clipboard.writeText(code.textContent)
            copyButton.innerHTML = '<i class="fas fa-check"></i> 已复制'
            copyButton.classList.add('copied')
            setTimeout(() => {
              copyButton.innerHTML = '<i class="fas fa-copy"></i> 复制'
              copyButton.classList.remove('copied')
            }, 2000)
            this.$message.success('复制成功')
          } catch (err) {
            this.$message.error('复制失败，请手动复制')
          }
        })

        // 将按钮添加到代码块
        buttonWrapper.appendChild(copyButton)
        pre.appendChild(buttonWrapper)
      })
    },

    /**
     * 发送文本消息
     */
    async sendMessage() {
      if ((!this.messageText.trim() && this.pastedImages.length === 0) || 
          !this.$store.state.userInfo || 
          this.countdown > 0) return;

      try {
        // 发送文本消息
        if (this.messageText.trim()) {
          const textMessage = {
            type: "text",
            content: this.messageText, // 直接发送包含 HTML 的内容
            name: this.$store.state.userInfo.nickname,
            senderId: this.$store.state.userInfo.id,
            avatar: this.$store.state.userInfo.avatar,
            sex: this.$store.state.userInfo.sex,
            replyId: this.selectedReplyMessage?.id || null,
            replyContent: this.selectedReplyMessage?.content || null,
            replyUserId: this.selectedReplyMessage?.userId || null,
            replyUserName: this.selectedReplyMessage?.name || null,
            roomId : this.currentChat.id,
            isgroup :  Number(this.currentChat.isgroup),
            toUserId : this.currentChat.friendId
          };
          
          // 立即将消息添加到当前聊天室的消息列表中（本地回显）
          const localMessage = {
            id: Date.now() + Math.random(), // 临时ID，等待服务器响应后更新
            type: "text",
            content: this.messageText,
            time: formatTime(new Date()),
            senderId: this.$store.state.userInfo.id,
            name: this.$store.state.userInfo.nickname,
            avatar: this.$store.state.userInfo.avatar,
            sex: this.$store.state.userInfo.sex,
            replyId: this.selectedReplyMessage?.id || null,
            replyContent: this.selectedReplyMessage?.content || null,
            replyUserName: this.selectedReplyMessage?.name || null,
            isPlaying: false
          };
          console.log(this.currentChat.id);
          
          // // 将消息添加到当前聊天室
          // if(this.currentChat.id === '1'){
          //   console.log('我是群聊');
            
          // }else{
          // this.currentChat.messages.push(localMessage);

          // }
          this.currentChat.messages.push(localMessage);

          
          // 更新聊天室的最后消息和时间
          this.currentChat.lastMessage = this.messageText;
          this.currentChat.lastTime = "刚刚";
          
          // 清空输入框
          this.$refs.messageInput.innerHTML = '';
          this.messageText = '';
          this.selectedReplyMessage = null;
          
          // 发送消息到服务器
          await sendMsg(textMessage);
        }

        // 清空输入框
        this.$refs.messageInput.innerHTML = '';
        this.messageText = '';
        this.selectedReplyMessage = null;

        // 依次发送图片
        for (const image of this.pastedImages) {
          const formData = new FormData();
          formData.append("file", image.file);
          
          const response = await uploadFileApi(formData, "chat");
          if (response.data) {
            await this.sendImage(response.data);
          }
        }

        this.startCountdown();
        this.shouldScrollToBottom = true;
        this.pastedImages = []; // 清空图片列表
      } catch (error) {
        console.error("发送消息失败:", error);
        // this.$message.error("发送失败，请重试");
      }
    },

    /**
     * 发送图片消息
     */
    async sendImage(imageData) {
      if (!this.$store.state.userInfo) return;

      const message = {
        type: "image",
        content: imageData,
        self: true,
        name: this.$store.state.userInfo.nickname,
        senderId: this.$store.state.userInfo.id,
        avatar: this.$store.state.userInfo.avatar,
        sex: this.$store.state.userInfo.sex,
        isgroup: this.currentChat.isgroup,
        roomId: this.currentChat.id,
        toUserId: this.currentChat.isgroup == 1 ? null : this.currentChat.id,
      };

      try {
        // 立即将图片消息添加到当前聊天室的消息列表中（本地回显）
        const localMessage = {
          id: Date.now() + Math.random(), // 临时ID，等待服务器响应后更新
          type: "image",
          content: imageData,
          time: formatTime(new Date()),
          senderId: this.$store.state.userInfo.id,
          name: this.$store.state.userInfo.nickname,
          avatar: this.$store.state.userInfo.avatar,
          sex: this.$store.state.userInfo.sex,
          isPlaying: false
        };
        
        // 将消息添加到当前聊天室
        this.currentChat.messages.push(localMessage);
        
        // 更新聊天室的最后消息和时间
        this.currentChat.lastMessage = "[图片]";
        this.currentChat.lastTime = "刚刚";
        
        const response = await sendMsg(message);
        this.shouldScrollToBottom = true; // 发送图片时设置为true
      } catch (error) {
        console.error("发送图片失败:", error);
        // this.$message.error("发送失败，请重试");
      }
    },

    /**
     * 滚动到底部
     */
    scrollToBottom() {
      const container = this.$refs.messageContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },

    /**
     * 插入表情
     */
    insertEmoji(emoji) {
      const img = `<img src="${emoji}" class="emoji" style="width: 30px; height: 30px; vertical-align: middle;">`;
      const editor = this.$refs.messageInput;
      editor.focus();
      document.execCommand('insertHTML', false, img);
      this.messageText = editor.innerHTML;
    },

    /**
     * 预览图片
     * @param src
     */
    previewImage(src) {
      this.$refs.imagePreview.show(src);
    },
    /**
     * 显示消息操作菜单
     * @param {Object} message 消息对象
     * @param {Event} event 鼠标事件
     */
    showMessageActions(message, event) {
      this.selectedMessage = message;
      this.showActionsMenu = true;

      // 计算菜单位置
      this.actionMenuPosition = {
        top: `${event.clientY}px`,
        left: `${event.clientX}px`,
      };

      // 添加点击事件监听
      setTimeout(() => {
        document.addEventListener("click", this.closeActionsMenu);
      }, 0);
    },

    /**
     * 关闭消息操作菜单
     */
    closeActionsMenu() {
      this.showActionsMenu = false;
      this.selectedMessage = null;
      document.removeEventListener("click", this.closeActionsMenu);
    },

    /**
     * 撤回消息
     */
    async recallMessage() {
      if (!this.selectedMessage) return;

      try {
        const data = { id: this.selectedMessage.id };
        // 调用撤回消息接口
        const response = await recallMsgApi(data);
      } catch (error) {
        this.$message.error(error.message || "撤回失败，请重试");
      }
      this.closeActionsMenu();
    },

    /**
     * 处理搜索
     */
    handleSearch() {
      this.$message.info("搜索功能暂未实现");
    },

    /**
     * 处理下载文件
     */
    async handleDownloadFile() {
      window.open(this.selectedMessage.content, '_blank');
      // try {
      //   let fileName = this.selectedMessage.fileName;
      //   let response = await fetch(this.selectedMessage.content);
      //   let blob = await response.blob();
      //   let blobUrl = URL.createObjectURL(blob);
      //   const link = document.createElement("a"); // 创建a标签
      //   link.href = blobUrl; // 下载链接
      //   link.download = fileName; // 下载的文件名
      //   document.body.appendChild(link);
      //   link.click();
      //   document.body.removeChild(link); // 下载完成后移除a标签
      //   URL.revokeObjectURL(blobUrl); // 释放URL对象
      // } catch (error) {
      //   this.$message.error("下载失败，请重试");
      // }
    },

    /**
     * 处理图片加载
     */
    handleImageLoad() {
      // 只有在需要滚动到底部时才执行
      if (this.shouldScrollToBottom) {
        this.scrollToBottom();
      }
    },

    /**
     * 加载更多历史消息
     */
    async loadMoreMessages() {
      if (this.loading || !this.hasMore) return;

      this.loading = true;
      this.shouldScrollToBottom = false;
      
      try {
        const container = this.$refs.messageContainer;
        
        // 检查容器是否存在
        if (!container) {
          console.warn('消息容器未找到');
          return;
        }
        
        const oldScrollHeight = container.scrollHeight;

        this.params.pageNum++;
        
        const response = await getChatMsgListApi(this.params);
        console.log(response);
        
        

        if (response.data && response.data.records && response.data.records.length > 0) {
          const formattedMessages = response.data.records.map((msg) => ({
            ...msg,
            time: formatTime(msg.time),
          }));

          this.currentChat.messages.unshift(...formattedMessages.reverse());
          // console.log("this.currentChat.messages:", this.currentChat.messages);
          
          if (response.data.records.length < this.params.pageSize) {
            this.hasMore = false;
          }

          this.$nextTick(() => {
            // 再次检查容器是否存在
            if (container) {
              const newScrollHeight = container.scrollHeight;
              container.scrollTop = newScrollHeight - oldScrollHeight;
              this.handlePreCode();
            }
          });
        } else {
          this.hasMore = false;
        }
      } catch (error) {
        console.error("加载历史消息失败:", error);
        this.$message.error("加载历史消息失败");
      } finally {
        this.loading = false;
        // console.log("this.currentChat.messages:", this.currentChat.messages);
        
      }
    },

    /**
     * 开始倒计时
     */
    startCountdown() {
      this.countdown = 3;
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
      this.countdownTimer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.countdownTimer);
        }
      }, 1000);
    },

    /**
     * 开始心跳
     */
    startHeartbeat() {
      this.stopHeartbeat(); // 确保之前的心跳已停止
      this.heartbeatTimer = setInterval(() => {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          // 发送心跳消息
          this.ws.send(
            JSON.stringify({
              type: "ping",
              timestamp: new Date().getTime(),
            })
          );
        } else {
          this.stopHeartbeat();
          this.reconnect();
        }
      }, this.heartbeatInterval);
    },

    /**
     * 停止心跳
     */
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }
    },

    /**
     * 重连WebSocket
     */
    reconnect() {
      // 如果不需要重连，直接返回
      if (!this.shouldReconnect) {
        return;
      }

      if (this.reconnectAttempts >= this.maxReconnectAttempts) {
        console.log("达到最大重连次数，停止重连");
        this.$message.error("网络连接异常，请刷新页面重试");
        return;
      }

      this.reconnectAttempts++;
      console.log(`第 ${this.reconnectAttempts} 次尝试重连...`);

      // 使用指数退避算法计算重连延迟
      const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);

      setTimeout(() => {
        // 再次检查是否需要重连
        if (this.shouldReconnect && this.$store.state.userInfo) {
          this.connectWebSocket();
        }
      }, delay);
    },

    //截取地址
    splitIpAddress(address) {
      return address ? address.split("|")[1] : "未知";
    },

    /**
     * 处理Enter键
     * @param {KeyboardEvent} event
     */
    handleEnterKey(event) {
      // 如果按下了Ctrl键，则插入换行
      if (event.ctrlKey) {
        const input = this.$refs.messageInput;
        const start = input.selectionStart;
        const end = input.selectionEnd;
        this.messageText =
          this.messageText.substring(0, start) +
          "\n" +
          this.messageText.substring(end);

        // 将光标移动到换行后的位置
        this.$nextTick(() => {
          input.selectionStart = input.selectionEnd = start + 1;
        });
      } else {
        // 否则发送消息
        this.sendMessage();
      }
    },

    /**
     * 处理@输入
     * @param {Event} event
     */
    handleInput(event) {
      const input = this.$refs.messageInput;
      this.messageText = input.innerHTML; // 使用 innerHTML 而不是 innerText 来保留 HTML 标签

      // 处理 placeholder
      if (input.innerHTML.trim() === '') {
        input.setAttribute('data-empty', 'true');
      } else {
        input.setAttribute('data-empty', 'false');
      }
    },

    /**
     * 处理@列表键盘事件
     * @param {KeyboardEvent} event
     */
    handleMentionKeydown(event) {
      if (!this.showMentionList) return;

      const filteredUsers = this.getFilteredUsers();

      switch (event.key) {
        case "ArrowDown":
          event.preventDefault();
          this.selectedMentionIndex = Math.min(
            this.selectedMentionIndex + 1,
            filteredUsers.length - 1
          );
          break;
        case "ArrowUp":
          event.preventDefault();
          this.selectedMentionIndex = Math.max(
            this.selectedMentionIndex - 1,
            0
          );
          break;
        case "Enter":
          event.preventDefault();
          if (this.selectedMentionIndex >= 0) {
            this.selectMentionUser(filteredUsers[this.selectedMentionIndex]);
          }
          break;
        case "Escape":
          event.preventDefault();
          this.showMentionList = false;
          break;
      }
    },

    /**
     * 选择要@的用户
     * @param {Object} user
     */
    selectMentionUser(user) {
      const input = this.$refs.messageInput;
      const text = input.innerText;
      const position = input.selectionStart;
      const lastAtIndex = text.lastIndexOf("@", position - 1);

      if (lastAtIndex !== -1) {
        this.messageText =
          text.substring(0, lastAtIndex) +
          `@${user.name} ` +
          text.substring(position);

        // 将光标移动到插入的@用户名后面
        this.$nextTick(() => {
          const newPosition = lastAtIndex + user.nickname.length + 2;
          input.focus();
          input.setSelectionRange(newPosition, newPosition);
        });
      }

      this.showMentionList = false;
    },

    /**
     * 获取过滤后的用户列表
     */
    getFilteredUsers() {
      return this.mentionUsers.filter((user) =>
        user.nickname.toLowerCase().includes(this.mentionFilter.toLowerCase())
      );
    },

    /**
     * 获取光标在textarea中的坐标
     */
    getCaretCoordinates(element, position) {
      const div = document.createElement("div");
      const styles = window.getComputedStyle(element);
      const properties = [
        "direction",
        "boxSizing",
        "width",
        "height",
        "overflowX",
        "overflowY",
        "borderTopWidth",
        "borderRightWidth",
        "borderBottomWidth",
        "borderLeftWidth",
        "paddingTop",
        "paddingRight",
        "paddingBottom",
        "paddingLeft",
        "fontStyle",
        "fontVariant",
        "fontWeight",
        "fontStretch",
        "fontSize",
        "fontSizeAdjust",
        "lineHeight",
        "fontFamily",
        "textAlign",
        "textTransform",
        "textIndent",
        "textDecoration",
        "letterSpacing",
        "wordSpacing",
      ];

      div.style.position = "absolute";
      div.style.visibility = "hidden";
      properties.forEach((prop) => {
        div.style[prop] = styles[prop];
      });

      div.textContent = element.value.substring(0, position);
      const span = document.createElement("span");
      span.textContent = element.value.substring(position) || ".";
      div.appendChild(span);
      document.body.appendChild(div);

      const coordinates = {
        top:
          span.offsetTop +
          parseInt(styles.borderTopWidth) +
          parseInt(styles.paddingTop),
        left:
          span.offsetLeft +
          parseInt(styles.borderLeftWidth) +
          parseInt(styles.paddingLeft),
      };

      document.body.removeChild(div);
      return coordinates;
    },

    /**
     * 在头像上右键时显示@选项
     */
    handleAvatarContextMenu(message, event) {
      event.preventDefault();
      // 不能@自己
      if (message.senderId === this.$store.state.userInfo.id) {
        return;
      }

      this.selectedMessage = message;
      this.showActionsMenu = true;

      // 计算菜单位置
      this.actionMenuPosition = {
        top: `${event.clientY}px`,
        left: `${event.clientX}px`,
      };

      // 添加点击事件监听
      setTimeout(() => {
        document.addEventListener("click", this.closeActionsMenu);
      }, 0);
    },

    /**
     * @用户
     */
    mentionUser() {
      if (!this.selectedMessage) return;
      const user = {
        nickname: this.selectedMessage.name,
      };

      // 在输入框末尾添加@用户
      const input = this.$refs.messageInput;
      const mentionText = `@${user.nickname} `;
      
      // 更新messageText
      this.messageText += mentionText;
      
      // 更新contenteditable div的内容
      input.innerHTML += mentionText;

      // 将光标移动到末尾
      const range = document.createRange();
      const selection = window.getSelection();
      
      // 将range设置到input的最后
      range.selectNodeContents(input);
      range.collapse(false); // false means collapse to end
      
      // 清除当前选择并应用新的range
      selection.removeAllRanges();
      selection.addRange(range);

      // 关闭菜单
      this.closeActionsMenu();

      // 聚焦输入框
      input.focus();
    },

    /**
     * 格式化消息内容
     */
    formatMessageContent(content) {
      if (content === '***') return content;

      // 保留已有的img标签，不需要替换
      if (content.includes('<img')) {
        // 使用 marked 解析 Markdown 内容
        const htmlContent = marked(content);

        if(!content.includes('code')){
          content = content.replace(/\n/g, '<br>')
        }

        // 如果内容已经包含<mention>标签，说明是发送时已经处理过的
        if (htmlContent.includes("<mention>")) {
          return htmlContent;
        }

        // 处理普通文本中的@格式
        return htmlContent.replace(/@(\S+)\s/g, "<mention>@$1</mention> ");
      }

      // 处理纯文本中的表情标记
      content = content.replace(/\((https?:\/\/[^\s)]+)\)/g, '<img src="$1" class="emoji" style="width: 22px; height: 22px; vertical-align: middle;">');

      // 继续处理其他格式
      const htmlContent = marked(content);

      if(!content.includes('code')){
        content = content.replace(/\n/g, '<br>')
      }

      if (htmlContent.includes("<mention>")) {
        return htmlContent;
      }

      return htmlContent.replace(/@(\S+)\s/g, "<mention>@$1</mention> ");
    },

    toggleList() {
      if (!this.isMobile) return;
      this.isListHidden = !this.isListHidden;
    },

    /**
     * 检查是否为移动设备
     */
    checkMobile() {
      const width = window.innerWidth;
      this.isMobile = width <= 768;
      // 在移动端时默认隐藏列表
      if (this.isMobile) {
        this.isListHidden = true;
      } else {
        this.isListHidden = false;
      }
    },

    selectFriend(friend) {
      this.selectedFriend = friend;
      // 可以在这里添加其他逻辑，比如获取与该好友的聊天记录等
    },

    async sendMessageToFriend(id) {
      console.log('发送信息给好友:', id);
      
      // 实现发送信息的逻辑
      const friendId = id;
      this.selectedFriend = null;
      this.currentNav = 'chat'
      // 查询聊天室 没用就创建
      
      const room = await getRoomWithUserApi(this.$store.state.userInfo.id,friendId);
      // 检查聊天室列表中是否有改聊天室
      const existingRoom = this.chatList.find(item => item.id === room.data.id);
  
  if (existingRoom) {
    // 如果找到了该聊天室
    console.log('找到了聊天室:', existingRoom);
    // 可以设置为当前聊天室
    this.switchChatRoom(existingRoom)
    
  } else {
    // 如果没有找到该聊天室，可以添加到聊天列表中
    console.log('未找到聊天室，可能需要添加到列表中');
    const chatRoom = await this.createChatRoom(room.data,friendId)
    console.log(chatRoom);
    
    this.chatList.push(chatRoom);
    // this.currentChat = chatRoom;
    console.log(chatRoom);
    this.switchChatRoom(chatRoom)
    
  }
      
      // this.$message.info(`发送信息给 ${this.selectedFriend.name}`);
    },
    async createChatRoom(room,friendId) {
    const friendInfo = await getFriendInfoApi(friendId)
    const lastmsg = await getLastMsg(room.id)
    console.log(lastmsg);
    const newRoom = {
        id: room.id,
        name: friendInfo.data.name,
        avatar: friendInfo.data.avatar,
        lastMessage:null,
        lastTime: null,
        isgroup: false,
      }
      if(lastmsg.data){
        newRoom.lastMessage = lastmsg.data.content;
        newRoom.lastTime = lastmsg.data.createTime;
      }
      return newRoom;
    },

    deleteFriend() {
      // 实现删除好友的逻辑
      this.$message.info(`删除好友 ${this.selectedFriend.name}`);
    },

    /**
     * 处理文件上传
     * @param event
     */
    async handleFileUpload(event) {
      showLoading();
      const file = event.target.files[0];
      if (!file) return;

      try {
        // 创建 FormData 对象
        const formData = new FormData();
        formData.append("file", file);

        // 调用上传接口
        const response = await uploadFileApi(formData, "chat");

        // 发送文件消息
        if (response.data) {
          //获取文件类型，如果是图片则是发送图片接口
          const fileType = file.type;
          if(fileType.includes('image')){
            await this.sendImage(response.data);
          }else{
            await this.sendFile(response.data, file.name, file.size);
          }
        }
      } catch (error) {
        console.error("文件上传失败:", error);
        this.$message.error("文件上传失败");
      } finally {
        hideLoading();
      }

      // 清空 input 的值，允许重复选择同一文件
      event.target.value = "";
    },

    /**
     * 发送文件消息
     */
    async sendFile(fileData, fileName, fileSize) {
      if (!this.$store.state.userInfo) return;

      const message = {
        type: "file",
        content: fileData,
        fileName: fileName,
        fileSize: fileSize,
        name: this.$store.state.userInfo.nickname,
        senderId: this.$store.state.userInfo.id,
        avatar: this.$store.state.userInfo.avatar,
        sex: this.$store.state.userInfo.sex,
        isgroup: this.currentChat.isgroup,
        roomId: this.currentChat.id,
        toUserId: this.currentChat.isgroup == 1 ? null : this.currentChat.id,
      };

      try {
        // 立即将文件消息添加到当前聊天室的消息列表中（本地回显）
        const localMessage = {
          id: Date.now() + Math.random(), // 临时ID，等待服务器响应后更新
          type: "file",
          content: fileData,
          fileName: fileName,
          fileSize: fileSize,
          time: formatTime(new Date()),
          senderId: this.$store.state.userInfo.id,
          name: this.$store.state.userInfo.nickname,
          avatar: this.$store.state.userInfo.avatar,
          sex: this.$store.state.userInfo.sex,
          isPlaying: false
        };
        
        // 将消息添加到当前聊天室
        this.currentChat.messages.push(localMessage);
        
        // 更新聊天室的最后消息和时间
        this.currentChat.lastMessage = "[文件]";
        this.currentChat.lastTime = "刚刚";
        
        const response = await sendMsg(message);
        this.shouldScrollToBottom = true; // 发送文件时设置为true
      } catch (error) {
        console.error("发送文件失败:", error);
        // this.$message.error("发送失败，请重试");
      }
    },

    /**
     * 格式化文件大小
     * @param {Number} size 文件大小（字节）
     * @returns {String} 格式化后的文件大小
     */
    formatFileSize(size) {
      if (size < 1024) return size + " B";
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + " KB";
      if (size < 1024 * 1024 * 1024)
        return (size / (1024 * 1024)).toFixed(2) + " MB";
      return (size / (1024 * 1024 * 1024)).toFixed(2) + " GB";
    },

    /**
     * 切换语音模式
     */
    toggleVoiceMode() {
      this.isVoiceMode = !this.isVoiceMode;
    },

    /**
     * 开始录音
     */
    startRecording() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        this.$message.error("当前浏览器不支持录音功能");
        return;
      }

      navigator.mediaDevices
        .getUserMedia({ audio: true })
        .then((stream) => {
          this.audioStartTime = new Date();
          this.mediaRecorder = new MediaRecorder(stream);
          this.mediaRecorder.start();
          this.audioChunks = [];

          this.mediaRecorder.ondataavailable = (event) => {
            this.audioChunks.push(event.data);
          };

          // 添加录音中的视觉反馈
          this.isRecording = true;
        })
        .catch((error) => {
          console.error("录音失败:", error);
          this.$message.error("录音失败，请检查麦克风权限");
        });
    },

    /**
     * 停止录音并上传语音
     */
    stopRecording() {
      if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
        this.audioEndTime = new Date();
        let recordingDuration = Math.ceil(
          (this.audioEndTime - this.audioStartTime) / 1000
        );
        if (recordingDuration < 3) {
          this.$message.error("录音时间太短，请重新录音");
          return;
        }
        this.mediaRecorder.stop();
        this.mediaRecorder.onstop = async () => {
          const audioBlob = new Blob(this.audioChunks, { type: "audio/wav" });
          const formData = new FormData();
          formData.append("file", audioBlob, new Date().getTime() + ".wav");

          try {
            const response = await uploadFileApi(formData, "chat");
            if (response.data) {
              await this.sendAudio(response.data, recordingDuration);
            }
          } catch (error) {
            console.error("语音上传失败:", error);
            this.$message.error("语音上传失败");
          }

          this.isRecording = false;
          if (this.mediaRecorder.stream) {
            this.mediaRecorder.stream
              .getTracks()
              .forEach((track) => track.stop());
          }
        };
      }
    },

    /**
     * 取消录音
     */
    cancelRecording() {
      if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
        this.mediaRecorder.stop();
        this.audioChunks = [];
        this.$message.info("录音已取消");
        this.isRecording = false; // 移除录音中的视觉反馈
        if (this.mediaRecorder.stream) {
          this.mediaRecorder.stream
            .getTracks()
            .forEach((track) => track.stop());
        }
      }
    },

    /**
     * 发送语音消息
     */
    async sendAudio(audioUrl, duration) {
      if (!this.$store.state.userInfo) return;

      const message = {
        type: "audio",
        content: audioUrl,
        duration: duration,
        name: this.$store.state.userInfo.nickname,
        senderId: this.$store.state.userInfo.id,
        avatar: this.$store.state.userInfo.avatar,
        sex: this.$store.state.userInfo.sex,
      };

      try {
        // 立即将语音消息添加到当前聊天室的消息列表中（本地回显）
        const localMessage = {
          id: Date.now() + Math.random(), // 临时ID，等待服务器响应后更新
          type: "audio",
          content: audioUrl,
          duration: duration,
          time: formatTime(new Date()),
          senderId: this.$store.state.userInfo.id,
          name: this.$store.state.userInfo.nickname,
          avatar: this.$store.state.userInfo.avatar,
          sex: this.$store.state.userInfo.sex,
          isPlaying: false
        };
        
        // 将消息添加到当前聊天室
        this.currentChat.messages.push(localMessage);
        
        // 更新聊天室的最后消息和时间
        this.currentChat.lastMessage = "[语音] " + duration + "秒";
        this.currentChat.lastTime = "刚刚";
        
        const response = await sendMsg(message);
        this.shouldScrollToBottom = true; // 发送语音时设置为true
      } catch (error) {
        console.error("发送语音失败:", error);
        // this.$message.error("发送失败，请重试");
      }
    },

    /**
     * 切换语音播放状态
     */
    toggleAudioPlayback(msg, event) {
      if (this.audio) {
        this.audio.pause();
        this.$set(msg, "isPlaying", false);
        this.audio = null;
        return;
      }
      this.audio = new Audio(msg.content);
      this.audio
        .play()
        .then(() => {
          this.$set(msg, "isPlaying", true);
          this.audio.onended = () => {
            this.$set(msg, "isPlaying", false);
            this.audio = null;
          };
        })
        .catch((error) => {
          this.audio = null;
          console.error("音频播放失败:", error);
          this.$message.error("音频播放失败，请检查音频格式或网络连接");
        });
    },

    /**
     * 格式化音频时长
     */
    formatAudioDuration(duration) {
      const minutes = Math.floor(duration / 60);
      const seconds = duration % 60;
      return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
    },

    /**
     * 滚动到指定消息
     */
    async scrollToMessage(messageId) {
        const container = this.$refs.messageContainer;
        let messageElement = container.querySelector(`[data-message-id="${messageId}"]`);

        // 如果消息元素不存在，尝试加载更多消息
        while (!messageElement && this.hasMore) {
            await this.loadMoreMessages(); // 确保等待加载完成
            messageElement = container.querySelector(`[data-message-id="${messageId}"]`);
        }

        // 如果找到消息元素，滚动到该位置
        if (messageElement) {
            const offset = 100; // 设置偏移量，单位为像素
            const topPosition = messageElement.offsetTop - offset;
            container.scrollTo({ top: topPosition, behavior: 'smooth' });

            // 添加激活效果
            messageElement.classList.add('active-message');
            setTimeout(() => {
                messageElement.classList.remove('active-message');
            }, 2000); // 3秒后移除激活效果
        } else {
            this.$message.error("未能找到该消息，请尝试手动加载更多历史消息。");
        }
    },
    /**
     * 回复菜单
     */
    replyToMessage() {
      this.selectedReplyMessage = this.selectedMessage;
      this.closeActionsMenu();
      this.$nextTick(() => {
        const input = this.$refs.messageInput;
        input.focus();
      });
    },
    /**
     * 取消回复
     */
    cancelReply() {
      this.selectedReplyMessage = null;
    },
    // 生成唯一的key
    generateUniqueKey(msg, index) {
      return msg.id || `msg-${msg.senderId}-${index}-${Date.now()}`;
    },
    /**
     * 处理粘贴事件
     * @param {ClipboardEvent} event
     */
    async handlePaste(event) {
      const items = event.clipboardData.items;
      
      for (let item of items) {
        if (item.type.startsWith('image/')) {
          //最多只能三张
          if (this.pastedImages.length >= 3) {
            this.$message.error("最多只能粘贴3张图片");
            return;
          }
          event.preventDefault();
          const file = item.getAsFile();
          
          if (file.size > 5 * 1024 * 1024) {
            this.$message.error("图片大小不能超过5MB");
            return;
          }

          // 创建预览
          const reader = new FileReader();
          reader.onload = (e) => {
            this.pastedImages.push({
              file: file,
              preview: e.target.result
            });
          };
          reader.readAsDataURL(file);
          break;
        }
      }
    },

    /**
     * 移除预览图片
     * @param {number} index
     */
    removeImage(index) {
      this.pastedImages.splice(index, 1);
    },

    /**
     * 清空聊天记录
     */
    clearChatHistory() {
      this.$confirm('确定要清空所有聊天记录吗？此操作不可恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际清空聊天记录的逻辑
        this.chatList.forEach(chat => {
          chat.messages = [];
        });
        this.$message.success('聊天记录已清空');
      }).catch(() => {
        // 用户取消操作
      });
    },

    /**
     * 导出聊天数据
     */
    exportChatData() {
      this.$message.info('聊天数据导出功能开发中...');
      // 实际导出逻辑可以在这里实现
    },

    /**
     * 检查更新
     */
    checkForUpdates() {
      this.$message.success('当前已是最新版本');
      // 实际检查更新逻辑可以在这里实现
    },

    /**
     * 显示帮助信息
     */
    showHelp() {
      this.$alert('聊天系统使用帮助文档', '使用帮助', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        message: `
          <div style="line-height: 1.6;">
            <h4>基本操作：</h4>
            <p>1. 点击左侧导航切换不同功能模块</p>
            <p>2. 在聊天页面可以发送文字、图片、文件和语音消息</p>
            <p>3. 右键消息可以进行撤回、回复等操作</p>
            <p>4. 使用@功能可以提醒特定用户</p>
            <br>
            <h4>设置说明：</h4>
            <p>1. 可以在设置中调整消息提醒、声音等选项</p>
            <p>2. 隐私设置可以控制好友添加和在线状态显示</p>
          </div>
        `
      });
    },

    /**
     * 备份设置
     */
    backupSettings() {
      this.$message.success('设置已备份到云端');
      // 实际备份逻辑可以在这里实现
    },

    /**
     * 恢复设置
     */
    restoreSettings() {
      this.$message.info('正在从云端恢复设置...');
      // 实际恢复逻辑可以在这里实现
    },

    /**
     * 查看统计信息
     */
    viewStatistics() {
      this.$alert('聊天统计信息', '数据统计', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        message: `
          <div style="line-height: 1.6;">
            <p>• 总消息数: 1286条</p>
            <p>• 总联系人: 24人</p>
            <p>• 总群组数: 5个</p>
            <p>• 在线时长: 45小时</p>
            <p>• 最活跃时段: 晚上8点-10点</p>
          </div>
        `
      });
    },

    /**
     * 意见反馈
     */
    feedback() {
      this.$prompt('请输入您的宝贵意见或建议', '意见反馈', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请详细描述您的想法...'
      }).then(({ value }) => {
        if (value && value.trim()) {
          this.$message.success('感谢您的反馈！');
          // 实际提交反馈逻辑可以在这里实现
        } else {
          this.$message.warning('请输入反馈内容');
        }
      }).catch(() => {
        // 用户取消操作
      });
    },

    /**
     * 切换主题
     */
    changeTheme() {
      this.$message.info('主题切换功能开发中...');
      // 实际主题切换逻辑可以在这里实现
    },

    /**
     * 表情管理
     */
    manageEmojis() {
      this.$message.info('表情管理功能开发中...');
      // 实际表情管理逻辑可以在这里实现
    },

    /**
     * 安全设置
     */
    securitySettings() {
      this.$alert('安全设置', '账户安全', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        message: `
          <div style="line-height: 1.6;">
            <p>• 修改密码</p>
            <p>• 登录设备管理</p>
            <p>• 隐私权限设置</p>
            <p>• 消息加密选项</p>
          </div>
        `
      });
    },

    /**
     * 关于系统
     */
    aboutSystem() {
      this.$alert('聊天系统 v1.0.0', '关于', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        message: `
          <div style="text-align: center; line-height: 1.6;">
            <p>zzzyh论坛系统内置聊天系统</p>
            <p>© 2025 聊天系统. 保留所有权利.</p>
            <p>开发者: Zheng Yuhang</p>
          </div>
        `
      });
    },

    /**
     * 处理鼠标滚轮事件，用于群规说明的滚动
     * @param {WheelEvent} event
     */
    handleScroll(event) {
      const container = event.currentTarget;
      const scrollTop = container.scrollTop;
      const scrollHeight = container.scrollHeight;
      const height = container.clientHeight;
      const delta = event.deltaY;

      // 计算新的滚动位置
      const newPosition = scrollTop + delta;

      // 防止滚动超出边界
      if (newPosition < 0) {
        container.scrollTop = 0;
      } else if (newPosition > scrollHeight - height) {
        container.scrollTop = scrollHeight - height;
      } else {
        container.scrollTop = newPosition;
      }
    },
  },
};
</script>

<style lang="scss" scoped>

.chat-item {
  position: relative;
  
  .avatar {
    position: relative;
    
    .unread-badge {
      position: absolute;
      top: -5px;
      right: -5px;
      background: #f56c6c;
      color: white;
      border-radius: 10px;
      font-size: 12px;
      min-width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 5px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      z-index: 1;
    }
  }
}

.chat-container {
  height: calc(100vh - 140px);
  display: grid;
  grid-template-columns: 80px 280px 1fr;
  background: var(--card-bg);
  border-radius: 12px;
  box-shadow: $shadow-lg;
  margin: $spacing-lg auto;
  overflow: hidden;
  max-width: 1200px;
  position: relative;
  z-index: 1;

  @media screen and (max-width: 768px) {
    height: 100vh;
    margin: 0;
    border-radius: 0;
    grid-template-columns: 80px 1fr;
    padding-top: 0; // 移除顶部padding
  }
}

.nav-sidebar {
  background: linear-gradient(180deg, #2c3e50 0%, #3498db 100%);
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;
  z-index: 200;

  @media screen and (max-width: 768px) {
    position: fixed;
    left: 0;
    top: 70px;
    bottom: 0;
    width: 80px;
  }

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgba(52, 152, 219, 0.1) 0%,
      rgba(44, 62, 80, 0.1) 100%
    );
    z-index: 1;
  }

  .nav-header {
    padding: $spacing-md;
    display: flex;
    justify-content: center;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    margin-bottom: $spacing-md;
    background: rgba(255, 255, 255, 0.05);
    position: relative;
    z-index: 2;

    .user-avatar {
      width: 48px;
      height: 48px;
      border-radius: 16px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.3s ease;
      border: 2px solid transparent;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);

      &:hover {
        border-color: rgba(255, 255, 255, 0.8);
        transform: scale(1.05) translateY(-2px);
        box-shadow: 0 8px 16px rgba(52, 152, 219, 0.3);
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .nav-menu {
    padding: $spacing-sm 0;
    display: flex;
    flex-direction: column;
    gap: $spacing-md;
    position: relative;
    z-index: 2;
    height: calc(100% - 100px); // 为底部源码按钮留出空间
    justify-content: flex-start;

    .nav-item {
      height: 64px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 6px;
      cursor: pointer;
      color: rgba(255, 255, 255, 0.7);
      transition: all 0.3s ease;
      position: relative;
      margin: 0 $spacing-sm;
      border-radius: 16px;
      backdrop-filter: blur(8px);
      &:hover {
        color: white;
        background: rgba(255, 255, 255, 0.1);
        transform: translateY(-1px);

        .nav-text {
          opacity: 1;
          transform: scale(1.02);
        }

        i {
          transform: scale(1.05);
        }

        &.chat-icon i {
          color: #2ecc71;
        }

        &.friends-icon i {
          color: #e74c3c;
        }

        &.groups-icon i {
          color: #f1c40f;
        }
      }

      &.active {
        color: white;
        background: rgba(255, 255, 255, 0.15);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

        &::before {
          content: "";
          position: absolute;
          left: -$spacing-sm;
          top: 50%;
          transform: translateY(-50%);
          width: 3px;
          height: 24px;
          background: white;
          border-radius: 0 4px 4px 0;
          box-shadow: 0 0 10px rgba(255, 255, 255, 0.4);
        }

        .nav-text {
          opacity: 1;
          color: white;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        &.chat-icon i {
          color: #2ecc71;
        }

        &.friends-icon i {
          color: #e74c3c;
        }

        &.groups-icon i {
          color: #f1c40f;
        }
      }

      i {
        font-size: 1.4em;
        transition: all 0.3s ease;
      }

      .nav-text {
        font-size: 0.85em;
        opacity: 0.8;
        transition: all 0.3s ease;
        font-weight: 500;
      }

      &::after {
        content: "";
        position: absolute;
        left: 50%;
        bottom: -$spacing-sm;
        transform: translateX(-50%);
        width: 3px;
        height: 3px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
      }

      &:last-child::after {
        display: none;
      }
    }
  }

  // 添加底部源码按钮样式
  .nav-bottom {
    position: absolute;
    bottom: $spacing-md;
    left: 0;
    right: 0;
    padding: 0 $spacing-sm;
    z-index: 2;

    .nav-item {
      height: 64px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 6px;
      cursor: pointer;
      color: rgba(255, 255, 255, 0.7);
      transition: all 0.3s ease;
      border-radius: 16px;
      backdrop-filter: blur(8px);
      text-decoration: none !important;

      &:hover {
        color: white;
        background: rgba(255, 255, 255, 0.1);
        transform: translateY(-1px);

        .nav-text {
          opacity: 1;
        }

        i {
          color: #f1c40f;
          transform: scale(1.1);
        }
      }

      i {
        font-size: 1.4em;
        transition: all 0.3s ease;
      }

      .nav-text {
        font-size: 0.85em;
        opacity: 0.8;
        transition: all 0.3s ease;
        font-weight: 500;
      }
    }
  }
}

.chat-list-container {
  background: var(--card-bg);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  overflow: hidden;

  @media screen and (max-width: 768px) {
    position: absolute;
    left: 80px;
    top: 0;
    bottom: 0;
    width: 280px;
    z-index: 150;
    background: var(--card-bg);
    transform: translateX(0);
    transition: transform 0.3s ease;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);

    &.mobile-hidden {
      transform: translateX(-280px);
    }
  }

  .search-box {
    padding: $spacing-md;
    border-bottom: 1px solid var(--border-color);
    background: var(--card-bg);
    position: relative;

    &::before {
      content: "\f002";
      font-family: "Font Awesome 5 Free";
      font-weight: 900;
      position: absolute;
      left: 24px;
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-secondary);
      font-size: 0.9em;
      opacity: 0.7;
    }

    input {
      width: 100%;
      padding: $spacing-sm $spacing-xl $spacing-sm 42px;
      border: 1px solid var(--border-color);
      border-radius: 24px;
      background: var(--input-bg);
      color: var(--text-primary);
      font-size: 0.9em;
      transition: all 0.3s ease;

      &:focus {
        outline: none;
        border-color: $primary;
        box-shadow: 0 0 0 3px rgba($primary, 0.1);

        & + .search-icon {
          color: $primary;
        }
      }

      &::placeholder {
        color: var(--text-secondary);
        opacity: 0.7;
      }
    }
  }

  .chat-list {
    flex: 1;
    overflow-y: auto;
    padding: $spacing-sm 0;
  }

  // 快捷操作组件样式
  .quick-actions {
    padding: $spacing-md;
    background: var(--card-bg);
    border-bottom: 1px solid var(--border-color);
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    
    .quick-actions-header {
      padding-bottom: $spacing-md;
      border-bottom: 1px solid var(--border-color);
      margin-bottom: $spacing-md;
      
      h3 {
        margin: 0;
        color: var(--text-primary);
        font-size: 1.1em;
        font-weight: 600;
      }
    }
    
    .quick-actions-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: $spacing-md;
    }
    
    .quick-action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: $spacing-lg;
      border-radius: 8px;
      background: var(--hover-bg);
      cursor: pointer;
      transition: all 0.3s ease;
      min-height: 100px;
      
      &:hover {
        background: var(--border-color);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
      
      i {
        font-size: 1.8em;
        margin-bottom: $spacing-sm;
        color: $primary;
      }
      
      span {
        font-size: 0.9em;
        color: var(--text-primary);
        text-align: center;
      }
    }
  }

  .friend-item {
    padding: $spacing-md;
    display: flex;
    align-items: center;
    gap: $spacing-md;
    margin: $spacing-sm $spacing-xs;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover,
    &.active {
      background: var(--hover-bg);
    }

    .avatar {
      width: 42px;
      height: 42px;
      flex-shrink: 0;
      user-select: none;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
      }
    }

    .friend-info {
      .name {
        font-size: 0.95em;
        font-weight: 500;
        color: var(--text-primary);
      }
    }
  }
}

.chat-item {
  padding: $spacing-md;
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: $spacing-md;
  margin: 0 $spacing-xs;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: var(--hover-bg);
  }

  &.active {
    background: var(--hover-bg);
  }

  .avatar {
    width: 42px;
    height: 42px;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      border-radius: 12px;
      object-fit: cover;
    }
  }

  .chat-info {
    min-width: 0; // 确保文本可以正确截断

    .name {
      margin-bottom: 4px;
      font-size: 0.95em;
      font-weight: 500;
      color: var(--text-primary);
    }

    .last-message {
      font-size: 0.85em;
      color: var(--text-secondary);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 170px;
      :deep(img) {
        width: 20px !important;
        height: 20px !important;
        vertical-align: middle;
      }
    }
  }

  .meta {
    flex-shrink: 0;

    .time {
      font-size: 0.8em;
      color: var(--text-secondary);
    }
  }
}

.empty-tip {
  padding: $spacing-lg;
  text-align: center;
  color: var(--text-secondary);
  font-size: 0.9em;
}

.chat-main {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--card-bg);
  border-left: 1px solid var(--border-color);
  position: relative;
  overflow: hidden;

  @media screen and (max-width: 768px) {
    grid-column: 2;
    padding-top: 60px; // 为header留出空间
    height: 100vh; // 设置全屏高度
    position: fixed; // 固定定位
    right: 0; // 固定在右侧
    left: 80px; // 留出左侧导航栏的空间
  }

  .chat-header {
    height: 70px;
    flex-shrink: 0;
    padding: $spacing-md $spacing-lg;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    background: var(--card-bg);
    z-index: 10;

    .user-info {
      display: flex;
      align-items: center;
      gap: $spacing-md;
      width: 100%;

      h3 {
        font-size: 1.1em;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0;
      }

      .toggle-list-btn {
        display: none;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: var(--hover-bg);
        cursor: pointer;
        margin-right: $spacing-sm;

        @media screen and (max-width: 768px) {
          display: flex;
        }

        &:hover {
          background: var(--border-color);
        }

        i {
        }
      }
    }

    .chat-actions {
      display: flex;
      gap: $spacing-sm;

      .action-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: var(--hover-bg);
        cursor: pointer;

        &:hover {
          background: var(--border-color);
        }

        i {
        }
      }
    }
  }

  .chat-messages {
    flex: 1;
    padding: $spacing-lg;
    overflow-y: auto; /* 支持鼠标滚动 */

    .message {
      display: flex;
      margin-bottom: $spacing-lg;

      .avatar {
        width: 42px;
        height: 42px;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          border-radius: 12px;
          object-fit: cover;
        }
      }

      .message-content {
        flex: 1;
        margin-left: $spacing-md;

        .message-header {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .name {
            font-size: 0.95em;
            font-weight: 500;
            color: var(--text-primary);
          }

          .time {
            font-size: 0.8em;
            color: var(--text-secondary);
          }
        }

        .message-body {
          margin-top: $spacing-sm;
          font-size: 0.9em;
          color: var(--text-primary);
          white-space: pre-wrap;
          word-wrap: break-word;

          :deep(img) {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
          }
        }
      }
    }
  }

  .chat-input {
    padding: $spacing-lg;
    border-top: 1px solid var(--border-color);

    .input-container {
      display: flex;
      gap: $spacing-sm;

      .input-field {
        flex: 1;
      }

      .send-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: var(--hover-bg);
        cursor: pointer;

        &:hover {
          background: var(--border-color);
        }

        i {
        }
      }
    }
  }
}

.settings-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--card-bg);
  border-left: 1px solid var(--border-color);
  overflow-y: auto; /* 支持鼠标滚动 */

  .settings-header {
    padding: $spacing-md $spacing-lg;
    border-bottom: 1px solid var(--border-color);
    background: var(--card-bg);
    h2 {
      margin: 0;
      font-size: 1.2em;
      font-weight: 600;
      color: var(--text-primary);
    }
  }

  .settings-content {
    flex: 1;
    padding: $spacing-lg;
    overflow-y: auto; /* 支持鼠标滚动 */

    .settings-card {
      margin-bottom: $spacing-lg;
      border-radius: 8px;
      box-shadow: $shadow-sm;

      :deep(.el-card__header) {
        background: var(--hover-bg);
        border-bottom: 1px solid var(--border-color);
        padding: $spacing-md $spacing-lg;
        font-weight: 600;
        color: var(--text-primary);
      }

      :deep(.el-card__body) {
        padding: $spacing-lg;
      }

      :deep(.el-form-item) {
        margin-bottom: $spacing-lg;
      }

      :deep(.el-form-item__label) {
        color: var(--text-primary);
        font-weight: 500;
      }

      :deep(.el-switch__label) {
        color: var(--text-secondary);
      }
    }

    .about-section {
      p {
        margin: $spacing-sm 0;
        color: var(--text-secondary);
        font-size: 0.9em;
      }
    }
  }
}

.messages {
    flex: 1;
    overflow-y: auto;
    padding: $spacing-md $spacing-lg;
    background: var(--bg);
    display: flex;
    flex-direction: column;
    gap: $spacing-md;
    -webkit-overflow-scrolling: touch; // 增加iOS滚动支持
    position: relative;
    z-index: 1;

    .message {
      display: flex;
      gap: $spacing-sm;
      align-items: flex-start;

      &.message-self {
        flex-direction: row-reverse;

        .message-content {
          align-items: flex-end;

          .message-text {
            background: $primary;
            color: white;
            border-radius: 16px 16px 4px 16px;
          }

          .message-header {
            flex-direction: row-reverse;
          }

          .sender-name {
            text-align: right;
            user-select: none;
          }
        }
      }

      .avatar {
        width: 36px;
        height: 36px;
        flex-shrink: 0;
        user-select: none;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
      }

      .message-content {
        display: flex;
        flex-direction: column;
        gap: 4px;
        max-width: 70%;

        .message-header {
          display: flex;
          align-items: center;
          gap: $spacing-sm;

          .sender-name {
            font-size: 0.85em;
            user-select: none;
            color: var(--text-secondary);
            .user-name {
              color: red;
            }
            .assistant-name {
              color: #b32ce9;
            }
          }
          .gender{
            font-size: 1em;
            &::before {
              content: '·';
            }
            .fa-mars{
              color: #007bff;
            }
            .fa-venus{
              color: pink;
            }
          }
        }

        .message-text {
          display: inline-block;
          min-width: 40px; // 添加最小宽度
          max-width: fit-content; // 让宽度适应内容
          background: var(--hover-bg);
          padding: $spacing-sm $spacing-md;
          border-radius: 16px 16px 16px 4px;
          color: var(--text-primary);
          word-break: break-word;
        
        }
      }
    }
  }

  .chat-input {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: $spacing-md;
    border-top: 1px solid var(--border-color);
    background: var(--card-bg);
    display: flex;
    gap: $spacing-md;
    z-index: 10;

    @media screen and (max-width: 768px) {
      position: fixed; // 固定定位
      left: 80px; // 与左侧导航栏对齐
    }

    .input-toolbar {
      display: flex;
      gap: $spacing-sm;
      align-items: center;

      :deep(.emoji-picker i) {
        color: #f1c40f !important;
      }

      .file-upload-btn {
        color: #2daba5;
      }
      .voice-toggle-btn {
        color: #e67e22;
      }
      .toolbar-btn {
        padding: $spacing-sm;
        border: none;
        background: none;
        cursor: pointer;
        border-radius: 4px;

        &:hover {
          background: var(--hover-bg);
        }
      }
    }
    .input-area {
      flex: 1;
      display: flex;
      gap: $spacing-sm;
    }

    textarea {
      flex: 1;
      border: 1px solid var(--border-color);
      border-radius: 8px;
      padding: $spacing-md;
      resize: none;
      height: 60px;
      background: var(--input-bg);
      color: var(--text-primary);

      &:focus {
        outline: none;
        border-color: $primary;
      }
    }

    button {
      width: 60px;
      border: none;
      border-radius: 8px;
      background: $primary;
      color: white;
      cursor: pointer;
      transition: all 0.3s ease;
      font-size: 1em;

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }

.message-text {
  background: var(--hover-bg);
  padding: $spacing-sm $spacing-md;
  border-radius: 12px 12px 12px 4px;
  color: var(--text-primary);
  max-width: 600px;

  // 添加深度选择器来处理v-html内容的样式
  :deep(mention) {
    color: rgb(84, 214, 231) !important;
    font-weight: 500;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }

  :deep(.emoji-img) {
    width: 1.5em;
    height: 1.5em;
    vertical-align: middle;
    margin: 0 2px;
    display: inline-block;
  }

  :deep(img.emoji) {
    width: 30px !important;
    height: 30px !important;
    vertical-align: middle;
    display: inline-block;
  }
}

.no-friend-selected {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);

  i {
    font-size: 4em;
    margin-bottom: $spacing-md;
  }
}

.no-chat-selected {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);

  i {
    font-size: 4em;
    margin-bottom: $spacing-md;
  }
}

.message-image {
  max-width: 200px;
  height: auto;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.05);
  }
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-actions {
  opacity: 0;
  transition: opacity 0.2s;
  padding: 4px;
  cursor: pointer;
  color: var(--text-secondary);

  &:hover {
    color: var(--text-primary);
  }
}

.message:hover .message-actions {
  opacity: 1;
}

.message-recalled {
  text-align: center;
  padding: $spacing-md;
  margin: 0 auto;

  span {
    background: var(--hover-bg);
    color: var(--text-secondary);
    font-size: 0.9em;
    padding: $spacing-sm $spacing-md;
    border-radius: 16px;
    display: inline-block;
  }
}

.message-time {
  margin-left: $spacing-sm;
  color: var(--text-secondary);
  &::after {
    content: '·';
  }
}

.message-actions-menu {
  position: fixed;
  background: var(--card-bg);
  border-radius: 8px;
  box-shadow: $shadow-lg;
  z-index: 1000;
  padding: $spacing-sm;
  min-width: 120px;

  .action-item {
    padding: $spacing-sm $spacing-md;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: $spacing-sm;
    color: var(--text-primary);

    &:hover {
      background: var(--hover-bg);
    }

    .fa-reply {
      color: #be1fde;
    }
    .fa-at {
      color: #0ab028;
    }
    .fa-download {
      color: #2daba5;
    }
    .fa-undo {
      color: #f5222d;
    }
    .fa-search {
      color: #1890ff;
    }
  }
}

.location {
  font-size: 12px;
  color: var(--text-secondary);
}

.author-tag {
  background: $primary;
  color: white;
  font-size: 12px;
  padding: 1px 6px;
  border-radius: 4px;
  margin-left: 4px;
}

.assistant-tag {
  background: #b32ce9;
  color: white;
  font-size: 12px;
  padding: 1px 6px;
  border-radius: 4px;
  margin-left: 4px;
}

// 对于自己发送的消息，修改@样式的颜色
.message-self {
  .message-content {
    align-items: flex-end;

    .message-text {
      background: $primary;
      color: white;
      border-radius: 16px 16px 4px 16px;
    }
  }
}

// 添加遮罩层样式
.mobile-overlay {
  display: none;

  @media screen and (max-width: 768px) {
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 140;
  }
}

.friend-details {
  padding: $spacing-lg;
  border-radius: 12px;
  margin: $spacing-lg auto;
  max-width: 600px;
  text-align: center;

  .avatar-wrapper {
    display: flex;
    justify-content: center;
    margin-bottom: $spacing-md;
  }


  h3 {
    font-size: 1.5em;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: $spacing-md;
  }

  .signature,
  .gender {
    font-size: 1em;
    color: var(--text-secondary);
    margin-bottom: $spacing-md;
  }
}

.message-file {
  display: flex;
  align-items: center;
  gap: $spacing-md;
  background: var(--hover-bg);
  padding: $spacing-sm $spacing-md;
  border-radius: 8px;
  color: var(--text-primary);
  cursor: pointer;
  max-width: 100%; // 确保文件框不会超出容器

  i {
    font-size: 1.5em;
    color: #3498db;
  }

  .file-info {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;

    a {
      text-decoration: none;
      color: var(--text-primary);
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .file-size {
      font-size: 0.85em;
      color: var(--text-secondary);
    }
  }
}

.chat-input {
  .voice-toggle-btn {
    color: #e67e22;
  }
  .voice-record-btn {
    width: 500px !important;

    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--input-bg);
    color: var(--text-primary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1em;
    transition: background 0.3s ease;

    &:hover,
    &:active,
    &.recording {
      background: #e74c3c;
      color: white;
    }
  }
}

.message-audio {
  display: flex;
  align-items: center;
  background: #e6f7ff;
  padding: 8px 12px;
  border-radius: 16px;
  cursor: pointer;
  max-width: 100%; // 确保语音消息不会超出容器
  position: relative;
  overflow: hidden;
  margin: 5px 0;

  .audio-bubble {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #333;

    i {
      font-size: 1.2em;
      color: #1890ff;
    }

    span {
      font-size: 0.85em;
      color: #555;
    }
  }

  &::after {
    content: "";
    position: absolute;
    left: -6px;
    top: 50%;
    transform: translateY(-50%);
    border: 6px solid transparent;
    border-right-color: #e6f7ff;
  }
}

.reply-message {
  background: var(--reply-message-bg); // 使用 CSS 变量
  padding: 2px 3px;
  border-radius: 8px;
  color: var(--text-secondary);
  cursor: pointer;

  .reply-content {
    font-size: 0.85em;
    color: var(--text-primary);
  }
}

// 设置页面样式
.settings-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--card-bg);
  border-left: 1px solid var(--border-color);
  overflow-y: auto; /* 支持鼠标滚动 */

  .settings-header {
    padding: $spacing-md $spacing-lg;
    border-bottom: 1px solid var(--border-color);
    background: var(--card-bg);
    h2 {
      margin: 0;
      font-size: 1.2em;
      font-weight: 600;
      color: var(--text-primary);
    }
  }

  .settings-content {
    flex: 1;
    padding: $spacing-lg;
    overflow-y: auto; /* 支持鼠标滚动 */

    .settings-card {
      margin-bottom: $spacing-lg;
      border-radius: 8px;
      box-shadow: $shadow-sm;

      :deep(.el-card__header) {
        background: var(--hover-bg);
        border-bottom: 1px solid var(--border-color);
        padding: $spacing-md $spacing-lg;
        font-weight: 600;
        color: var(--text-primary);
      }

      :deep(.el-card__body) {
        padding: $spacing-lg;
      }

      :deep(.el-form-item) {
        margin-bottom: $spacing-lg;
      }

      :deep(.el-form-item__label) {
        color: var(--text-primary);
        font-weight: 500;
      }

      :deep(.el-switch__label) {
        color: var(--text-secondary);
      }
    }

    .about-section {
      p {
        margin: $spacing-sm 0;
        color: var(--text-secondary);
        font-size: 0.9em;
      }
    }
  }
}

// 在导航菜单样式中添加设置图标样式
.nav-menu {
  .nav-item.settings-icon {
    &.active {
      &.settings-icon i {
        color: #9b59b6; // 紫色
      }
    }

    &:hover {
      &.settings-icon i {
        color: #9b59b6; // 紫色
      }
    }
  }
}

.reply-preview {
  background: var(--hover-bg);
  padding: $spacing-sm $spacing-md;
  border-radius: 8px;
  color: var(--text-secondary);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-sm;
  position: absolute; /* 绝对定位 */
  bottom: 100%; /* 放在输入框上方 */
  left: 50%; /* 水平居中 */
  transform: translateX(-50%); /* 水平居中调整 */
  width: calc(100% - 2 * $spacing-md); /* 与输入框宽度一致 */
  
  // 超出隐藏
  .reply-title{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
  }
  i {
    cursor: pointer;
    color: var(--text-primary);
  }
}

:deep(ol) {
  padding-left: $spacing-md !important;
}

:deep(ul) {
  padding-left: $spacing-md !important;
}

:deep(pre) {
    margin: 1em 0;
    position: relative;
    background: #282c34;
    border-radius: 6px;
    padding-top: 2.5em;
    overflow: auto;


    /* 调整代码内容的样式 */
    code {
      display: block;
      padding: 1em;
      padding-left: 1em;
      /* 增加左侧padding */
      margin-left: 0;
      /* 移除margin */
      overflow-x: auto;
      font-family: 'Fira Code', monospace;
      font-size: 14px;
      line-height: 1.5;
      position: relative;
      max-height: 500px;

    }

    /* 添加仿 macOS 风格的按钮 */
    &::before {
      content: '';
      position: absolute;
      top: 12px;
      left: 12px;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: #ff5f56;
      box-shadow:
        20px 0 0 #ffbd2e,
        40px 0 0 #27c93f;
    }

    /* 复制按钮容器 */
    .code-header {
      position: absolute;
      top: 8px;
      right: 12px;
      z-index: 2;
      opacity: 0;
      transition: opacity 0.2s ease;
    }

    /* 显示复制按钮 */
    &:hover .code-header {
      opacity: 1;
    }

    /* 复制按钮样式 */
    .copy-button {
      padding: 4px 8px;
      background: rgba(255, 255, 255, 0.1);
      border: none;
      border-radius: 4px;
      color: #abb2bf;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      gap: 4px;

      i {
        font-size: 14px;
      }

      &:hover {
        background: rgba(255, 255, 255, 0.2);
        color: #fff;
      }

      &.copied {
        background: #98c379;
        color: #fff;
      }
    }
  }

.message {
    .active-message {
        background-color: rgb(222 22 22 / 55%) !important; 
        transition: background-color 0.2s ease !important;
    }
}

// 添加以下全局样式
:deep(body) {
  &.scroll-disabled {
    overflow: hidden !important;
  }
}

.load-more-wrapper {
  display: flex;
  justify-content: center;
  padding: $spacing-md;
  margin-bottom: $spacing-md;
}

.no-chat-selected {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);

  i {
    font-size: 4em;
    margin-bottom: $spacing-md;
  }
}

.load-more-btn {
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  color: var(--text-primary);
  padding: $spacing-sm $spacing-lg;
  border-radius: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: $spacing-sm;
  transition: all 0.3s ease;

  &:hover {
    background: var(--hover-bg);
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  i {
    font-size: 0.9em;
  }
}

.groups-info-banner {
  display: flex;
  align-items: center;
  padding: $spacing-md;
  margin: $spacing-sm $spacing-xs;
  background: var(--hover-bg);
  border-radius: 8px;
  border-left: 4px solid $primary;
  
  .fa-info-circle {
    color: $primary;
    font-size: 1.2em;
    margin-right: $spacing-sm;
  }
  
  .groups-info-text {
    flex: 1;
    
    p {
      margin: 0;
      font-size: 0.9em;
      color: var(--text-primary);
      
      &:first-child {
        font-weight: 500;
      }
    }
    
    .info-subtext {
      font-size: 0.8em;
      color: var(--text-secondary);
      margin-top: 4px;
    }
  }
}

// 添加响应式样式
@media screen and (max-width: 768px) {
  .message {
    .message-content {
      max-width: 85%; // 在移动端可以适当增加最大宽度

      .message-text {
        font-size: 0.95em; // 移动端可以稍微调整字体大小
      }
    }
  }
}

.input-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: $spacing-sm;
}

.paste-preview {
  display: flex;
  flex-wrap: wrap;
  gap: $spacing-sm;
  padding: $spacing-sm;
  background: var(--hover-bg);
  border-radius: 8px;
  min-height: 60px;
}

.pasted-image {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  i {
    position: absolute;
    top: 2px;
    right: 2px;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 4px;
    border-radius: 50%;
    cursor: pointer;
    font-size: 12px;
    
    &:hover {
      background: rgba(0, 0, 0, 0.7);
    }
  }
}

.message-input {
  flex: 1;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: $spacing-md;
  min-height: 60px;
  max-height: 150px;
  overflow-y: auto;
  background: var(--input-bg);
  color: var(--text-primary);
  outline: none;
  word-break: break-word;

  &:focus {
    border-color: $primary;
  }

}

.no-group-selected {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  padding: $spacing-lg;
  background: linear-gradient(135deg, rgba(52, 152, 219, 0.05) 0%, rgba(44, 62, 80, 0.05) 100%);
  border-radius: 12px;
  margin: $spacing-md;
  animation: fadeInUp 0.6s ease-out;

  .group-info-container {
    max-width: 600px;
    width: 100%;
    text-align: center;
    background: var(--card-bg);
    border-radius: 16px;
    padding: $spacing-xl;
    box-shadow: $shadow-lg;
    border: 1px solid var(--border-color);
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
    }

    h3 {
      color: var(--text-primary);
      font-size: 1.8em;
      margin-bottom: $spacing-lg;
      font-weight: 600;
      position: relative;
      display: inline-block;
      
      &::after {
        content: "";
        position: absolute;
        bottom: -8px;
        left: 50%;
        transform: translateX(-50%);
        width: 60px;
        height: 3px;
        background: linear-gradient(90deg, $primary, #3498db);
        border-radius: 3px;
      }
    }

    .group-description {
      background: var(--hover-bg);
      border-radius: 12px;
      padding: $spacing-lg;
      margin-bottom: $spacing-xl;
      border: 1px solid var(--border-color);
      transition: all 0.3s ease;
      box-shadow: $shadow-sm;

      &:hover {
        transform: translateY(-3px);
        box-shadow: $shadow-md;
      }

      p {
        color: var(--text-primary);
        margin-bottom: $spacing-md;
        line-height: 1.6;
        font-size: 1.1em;
      }

      .group-features {
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;
        gap: $spacing-lg;
        margin-top: $spacing-md;

        .feature-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: $spacing-sm;
          padding: $spacing-md $spacing-lg;
          border-radius: 12px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          cursor: default;
          min-width: 120px;
          background: rgba(255, 255, 255, 0.05);
          backdrop-filter: blur(10px);
          border: 1px solid rgba(255, 255, 255, 0.1);

          &:hover {
            background: linear-gradient(135deg, rgba($primary, 0.2), rgba(#3498db, 0.2));
            transform: translateY(-5px) scale(1.05);
            box-shadow: 0 8px 16px rgba(52, 152, 219, 0.2);
          }

          i {
            font-size: 2em;
            color: $primary;
            margin-bottom: $spacing-sm;
            transition: all 0.3s ease;
          }

          span {
            color: var(--text-primary);
            font-size: 1em;
            font-weight: 500;
          }
        }
      }
    }

    .group-rules {
      background: var(--hover-bg);
      border-radius: 12px;
      padding: $spacing-lg;
      margin-bottom: $spacing-xl;
      text-align: left;
      border: 1px solid var(--border-color);
      transition: all 0.3s ease;
      box-shadow: $shadow-sm;

      &:hover {
        transform: translateY(-3px);
        box-shadow: $shadow-md;
      }

      h4 {
        color: var(--text-primary);
        margin-top: 0;
        margin-bottom: $spacing-md;
        display: flex;
        align-items: center;
        gap: $spacing-sm;
        font-size: 1.3em;
        font-weight: 600;

        i {
          color: $primary;
        }
      }

      ul {
        padding-left: 1.5em;
        margin: 0;

        li {
          margin-bottom: $spacing-sm;
          color: var(--text-primary);
          line-height: 1.6;
          padding: $spacing-xs 0;
          border-bottom: 1px dashed rgba($primary, 0.1);
          transition: all 0.2s ease;

          &:hover {
            color: $primary;
            padding-left: $spacing-sm;
          }

          &:last-child {
            border-bottom: none;
          }
        }
      }
    }

    .group-note {
      background: linear-gradient(135deg, rgba($primary, 0.1), rgba(#3498db, 0.1));
      border-radius: 12px;
      padding: $spacing-lg;
      border-left: 4px solid $primary;
      text-align: left;
      transition: all 0.3s ease;

      &:hover {
        background: linear-gradient(135deg, rgba($primary, 0.15), rgba(#3498db, 0.15));
        transform: translateY(-2px);
      }

      p {
        margin: 0;
        color: var(--text-primary);
        display: flex;
        align-items: flex-start;
        gap: $spacing-sm;
        line-height: 1.5;
        font-size: 1em;

        i {
          color: $primary;
          font-size: 1.2em;
          margin-top: 3px;
          flex-shrink: 0;
        }
      }

      .note-subtext {
        font-size: 0.95em;
        color: var(--text-secondary);
        margin-top: $spacing-sm;
        padding-left: 1.7em;
        font-style: italic;
      }
    }
  }
}

// 添加动画关键帧
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>